<?php
namespace Portal\Domain\Iadminossms;

class Kaifain extends Base {

    public function send($mobile, $params, $context) {
        $params = array_values($params); // 准备顺序替换 @

        $accessKey = $context['smsSupplier']['sms_supplier_config']['AccessKey'];;
        $content = $context['smsTpl']['sms_tpl_content'];
        $contentArr = explode('@', $content);

        $contentBind = '';
        foreach ($contentArr as $pos => $it) {
            $contentBind .= $it . (isset($params[$pos]) ? $params[$pos] : '');
        }

        return $this->doSend($accessKey, $mobile, $contentBind);
    }

    protected function doSend($accessKey, $mobile, $content) {
        $curl = curl_init();
        $mobile = is_array($mobile) ? implode(',', $mobile) : $mobile;

        $params = array(
            'key' => $accessKey, 
            'mobile' => $mobile,
            'content' => $content,
        );
        $url = 'https://binstd.apistd.com/sms/send?' . http_build_query($params);

        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
        ]);

        $response = curl_exec($curl);

        curl_close($curl);
        $arr = json_decode($response, true);

        if (!is_array($arr) || !isset($arr['status']) || $arr['status'] != '0') {
            \PhalApi\DI()->logger->info("Iadminossms Kaifain failed to send {$mobile} with {$content} ", $response);
            return false;
        } else {
            \PhalApi\DI()->logger->debug("Iadminossms Kaifain succeed to send {$mobile} with {$content} ", $response);
        }

        return true;
    }
}
